// jokerye-20180928

//nodejs 内置对象
const path = require('path')

const webpack = require('webpack')

const chalk = require('chalk')

//插件作用：从入口js文件中，分离出css成独立文件
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')

//插件作用：清理目录
const CleanWebpackPlugin = require('clean-webpack-plugin')

//插件作用：copy目录文件到指定目录
const CopyWebpackPlugin = require('copy-webpack-plugin')

//把css 、js 集合到html中，生成新的html
const HtmlWebpackPlugin = require('html-webpack-plugin')

//监听打包过程
const ProgressBarPlugin = require('progress-bar-webpack-plugin')

//配置静态资源的前缀
const website = {
    publicPath: "/"
}

//生成多页面配置
const getHtmlConfig = function(name,title="Output Management"){
    return {

        title: title,

        //是对html文件进行压缩
        minify: {
            removeAttributeQuotes: false
        },

        //为了开发中js有缓存效果，所以加入hash，这样可以有效避免缓存JS。
        hash: true,

        // inject:true,

        // loader: "raw-loader",

        //是要打包的html模版路径和文件名称。 此处需要插件html-withimg-loader和生成html配置title有冲突，去掉即可。
        //插件是用来做html包含用
        template: 'html-withimg-loader!' + path.resolve(__dirname, './src/') + `/${name}.html`,

        filename: path.resolve(__dirname, './dist/') + `/${name}.html`,

        //分别打包，common单独分离
        chunks:[name,'common'],
    }
}

module.exports = {

    //wp4新增属性
    mode: "development",

    entry: {

        //入口1
        index: './src/js/index.js',

    },
    output: {
        path: path.join(__dirname, 'dist'), // 出口目录，dist文件
        filename: 'js/[name].js?t=[hash]', //这里name就是打包出来的文件名，因为是单入口，就是main，多入口下回分解
        publicPath: website.publicPath
    },
    optimization: {

        //大概是分离公共模块成独立js文件吧
        splitChunks: {
          cacheGroups: {
            commons: {
              chunks: 'initial',
              minChunks: 2,
              maxInitialRequests: 5, // The default limit is too small to showcase the effect
              minSize: 0, // This is example is too small to create commons chunks
              name: 'common'
            }
          }
        }
    },
    module: {
        rules: [{
                test: /\.css$/,
                use: ExtractTextWebpackPlugin.extract({
                    fallback: 'style-loader',
                    use: ['css-loader', 'postcss-loader']
                }),
                include: path.join(__dirname, 'src'), //限制范围，提高打包速度
                exclude: /node_modules/
            },
            {
                test: /\.(png|jpg|jpeg|gif|svg)/,
                use: {
                    loader: 'url-loader',
                    options: {
                        outputPath: 'img/', // 图片输出的路径
                        limit: 5 * 1024
                    }
                }
            },

            //less处理及打包
            {
                test: /\.less$/,
                use: ExtractTextWebpackPlugin.extract({
                    use: [{
                        loader: "css-loader"
                    },{
                        loader: "postcss-loader"
                    }, {
                        loader: "less-loader"
                    }],
                    // use style-loader in development
                    fallback: "style-loader"
                })
            }
        ]

    },
    plugins: [
        // new CleanWebpackPlugin([path.join(__dirname, 'dist/')]),
        new HtmlWebpackPlugin(getHtmlConfig("index")),
        // new webpack.DefinePlugin({
        //     NODE_ENV:JSON.stringify(process.env.NODE_ENV)
        // }),
        new ExtractTextWebpackPlugin({
            filename: 'css/[name].css?t=[hash]',
            // allChunks:true
        }),
        // new CopyWebpackPlugin([
        //     {
        //       from: path.resolve(__dirname, 'dist'),
        //       to: path.resolve(__dirname, 'merchant'),
        //       ignore: ['.*'],
        //       copyUnmodified: true
        //     }
        //   ]),
          new ProgressBarPlugin({
            format: '  build [:bar] ' + chalk.green.bold(':percent') + ' (:elapsed seconds)'
          })
      
    ],
    devServer: {
        contentBase: path.join(__dirname, "dist"), //静态文件根目录
        port: 9090, // 端口
        host: 'localhost',
        overlay: true,
        compress: true // 服务器返回浏览器的时候是否启动gzip压缩
    }
}